﻿#include "CLS_WgtItemToolBar.h"
#include <QMenu>
#include <QPainter>
#include <QApplication>

CLS_WgtItemToolBar::CLS_WgtItemToolBar(QWidget *_pParent):
    QToolBar(_pParent)
{
    connect(this, &CLS_WgtItemToolBar::actionTriggered, this, &CLS_WgtItemToolBar::SlotTriggered);
}

void CLS_WgtItemToolBar::SetLang(const QString &_qstrLang)
{
    Q_UNUSED(_qstrLang);
}

void CLS_WgtItemToolBar::LoadStyleSheet(const QString &_qstrStyle)
{
    setStyleSheet(_qstrStyle);
}

void CLS_WgtItemToolBar::paintEvent(QPaintEvent *_pEvent)
{
    //TODO 临时解决方案，后续有其他方案可以替换
    Q_UNUSED(_pEvent);
    QVariant qvarSkin = qApp->property("skin");
    QColor qcolor;
    if(!qvarSkin.isValid())
    {
        qcolor.setNamedColor("#196CDC");  //默认用深色
    }

    QString qstrSkin = qvarSkin.toString();
    if("dark" == qstrSkin)
    {
        qcolor.setNamedColor("#196CDC");
    }
    else if("light" == qstrSkin)
    {
        qcolor.setNamedColor("#1DC100");
    }
    else
    {
        qcolor.setNamedColor("#196CDC");
    }

    QPainter ptToolBar(this);
    QPen qpBorder;
    qpBorder.setWidth(1);       //设置线宽
    qpBorder.setColor(qcolor);
    ptToolBar.setPen(qpBorder);
    ptToolBar.setBrush(qcolor);
    ptToolBar.drawRect(this->rect());
}

void CLS_WgtItemToolBar::Init(const QVector<CLS_ItemButton> &_vecBtnList, const QString _qstrItemId)
{
    m_qstrItemId = _qstrItemId;
    QList<QAction *> listActions;
    for (int i = 0; i < _vecBtnList.size(); ++i)
    {
        CLS_ItemButton clsItem = _vecBtnList.at(i);
        QAction *pAction = new QAction(QIcon(clsItem.m_qstrIcon), clsItem.m_qstrName);
        pAction->setCheckable(clsItem.m_blCheckedEnable);
        pAction->setChecked(clsItem.m_blChecked);
        pAction->setToolTip(clsItem.m_qstrToolTip);
        QVariant qvaData;
        qvaData.setValue(clsItem);
        pAction->setData(qvaData);
        listActions.append(pAction);
    }

    addActions(listActions);
}

void CLS_WgtItemToolBar::SlotTriggered(QAction *_pAction)
{
    if (nullptr == _pAction)
    {
        return;
    }

    QVariant itemData = _pAction->data();
    if (!itemData.isValid() || !itemData.canConvert<CLS_ItemButton>())
    {
        return;
    }

    CLS_ItemButton clsItem = itemData.value<CLS_ItemButton>();
    clsItem.m_blChecked = _pAction->isChecked();
    clsItem.m_blCheckedEnable = _pAction->isCheckable();
    emit SignTriggered(m_qstrItemId, clsItem);
}
